<template>
  <div class="UserIndexDialog">
    <el-dialog
      :close-on-click-modal="false"
      :title="dialog.skuObj?.skuId ? '编辑商品' : '新增商品'"
      :visible="dialog.visible"
      width="630px"
      :before-close="closeFn"
    >
      <span>
        <el-form ref="newSkuForm" :model="newSkuForm" :rules="newSkuFormRules" label-width="140px">
          <el-form-item label="商品名称：" prop="skuName">
            <el-input v-model.trim="newSkuForm.skuName"
            placeholder="请输入"
            maxlength="15"
            show-word-limit
            ></el-input>
          </el-form-item>
          <el-form-item label="品牌：" prop="brandName">
            <el-input v-model.trim="newSkuForm.brandName"
            placeholder="请输入"
            maxlength="10"
            show-word-limit
            ></el-input>
          </el-form-item>
          <el-form-item label="价格：" prop="price">
            <el-input-number
              v-model.number="newSkuForm.price"
              controls-position="right"
              class="number"
              :min="0.01"
              :precision="2"
              :step="0.1"
            ></el-input-number>
          </el-form-item>
          <el-form-item label="商品类型：" prop="classId">
            <el-select v-model="newSkuForm.classId" placeholder="请选择">
              <el-option
              v-for="item in SkuList"
              :key="item.classId"
              :label="item.className"
              :value="item.classId"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="规格：" prop="unit">
            <el-input v-model.trim="newSkuForm.unit"
            placeholder="请输入"
            maxlength="10"
            show-word-limit
            ></el-input>
          </el-form-item>
          <el-form-item label="商品图片" prop="skuImage">
            <el-upload
              action="baseUrl"
              class="avatar-uploader"
              :show-file-list="false"
              :before-upload="beforeAvatarUpload"
              >
              <img v-if="newSkuForm.skuImage" :src="newSkuForm.skuImage" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              <template #tip><br>支持扩展名：jpg、png，文件不得大于100kb</template>
            </el-upload>
          </el-form-item>
        </el-form>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeFn" size="medium">取消</el-button>
        <!-- 新建人员确定 -->
        <el-button v-if="dialog.skuObj?.skuId" type="primary" size="medium" @click="putGood">确定</el-button>
        <!-- 修改人员确定 -->
        <el-button v-else type="primary" size="medium" @click="pushGood">确定</el-button>
      </span>
    </el-dialog>
    <!-- 弹出框结束 -->
  </div>
</template>

<script>
import { updataImg } from '@/api/Equipment'
import { addGoods, getSKU, putGoods } from '@/api/skuAPIs'
export default {
  props: {
    dialog: {
      type: Object,
      required: true
    }
  },
  data () {
    return {
      // 表单信息
      newSkuForm: {
        skuName: '',
        brandName: '',
        price: '',
        classId: '',
        unit: '',
        skuImage: ''
      },
      // 表單校驗
      newSkuFormRules: {
        skuName: [{ required: true, message: '商品名称不能为空' }],
        brandName: [{ required: true, message: '品牌不能为空' }],
        price: [{ required: true, message: '价格不能为空' }],
        classId: [{ required: true, message: '商品类型不能为空' }],
        unit: [{ required: true, message: '规格不能为空' }],
        skuImage: [{ required: true, message: '商品图片未上传' }]
      },
      // 商品类型列表
      SkuList: []
    }
  },
  created () {
    this.getSKU()
  },
  methods: {
    async closeFn () {
      // 重置状态
      this.$emit('update:dialog', {
        visible: false, // 是否显示
        skuObj: {}
      })
      // 重置表单状态
      this.newSkuForm = {
        skuName: '',
        brandName: '',
        price: '',
        classId: '',
        unit: '',
        skuImage: ''
      }
      await this.$refs.newSkuForm.resetFields()
    },
    // 获取SKU列表
    async getSKU () {
      const { data: { currentPageRecords: SkuList } } = await getSKU({
        pageSize: 114514,
        pageIndex: 1
      })
      this.SkuList = SkuList
    },
    // 图片上传
    async beforeAvatarUpload (file) {
      console.log(file)
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'
      const isLt = file.size / 1024 / 1024 < 0.1
      let fileType = false
      if (isJPG) {
        fileType = true
      } else if (isPNG) {
        fileType = true
      } else {
        this.$message.error('上传头像图片只能是 JPG / PNG 格式!')
      }
      if (!isLt) {
        this.$message.error('上传头像图片大小不能超过 100kb!')
      }
      if (fileType && isLt) {
        const formData = new FormData()
        formData.append('fileName', file)
        const { data } = await updataImg(formData)
        this.newSkuForm.skuImage = data
        console.log(this.newSkuForm.skuImage)
      }
      return fileType && isLt
    },
    // 制作一个可以用于上传的表单数据
    goodForm () {
      const newObj = {}
      for (const key in this.newSkuForm) {
        if (key === 'price') {
          newObj[key] = this.newSkuForm[key] * 100
        } else {
          newObj[key] = this.newSkuForm[key]
        }
      }
      return newObj
    },
    // 上传商品
    async pushGood () {
      const newArr = this.goodForm()
      try {
        await this.$refs.newSkuForm.validate()
        await addGoods(newArr)
        this.$message.success('您进行了一个提交的成功')
        this.$parent.searchSKUList(true)
        this.closeFn()
      } catch (error) {
        console.log(error)
      }
    },
    // 更新商品
    async putGood () {
      const newArr = this.goodForm()
      try {
        await this.$refs.newSkuForm.validate()
        await putGoods({
          id: this.dialog.skuObj.skuId,
          data: newArr
        })
        this.$message.success('您进行了一个更新的成功')
        this.$parent.searchSKUList(true)
        this.closeFn()
      } catch (error) {
        console.log(error)
      }
    }
  },
  watch: {
    dialog: {
      handler (newVal) {
        if (newVal.skuObj?.skuId) {
          for (const key in this.newSkuForm) {
            this.newSkuForm[key] = newVal.skuObj[key]
          }
        }
      },
      deep: true // 深入監聽
    }
  }
}
</script>

<style lang="scss" scoped>
.UserIndexDialog {
  .el-form{
    padding-right: 40px;
    .el-select {
      width: 100%;
    }
    .el-input-number {
      width: 100%;
    }
  }
  ::v-deep .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    background: #f3f6fb;
    padding: 5px;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 78px;
    height: 78px;
    line-height: 78px;
    text-align: center;
  }
  .avatar {
    width: 78px;
    height: 78px;
    display: block;
  }
}
</style>
